package wiki.zimo.certificate_manage.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
 *
 * @author 子墨
 * @date 2018/10/13 23:27
 * @describe 文件 上传工具类
 */
@Service
public class FileSaveService {

    @Value("${file.upload-path}")
    private String uploadPath;// 文件保存路径

    /**
     * 文件保存方法
     * @author 子墨
     * @date 2018/10/13 23:38
     * @params [file]
     * @return java.lang.String
     */
    public String savaFile(MultipartFile file){
        String path = null;
        // 存储服务器路径
        File dir = new File(uploadPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        if(file != null){
            try {
                path = doSave(uploadPath,file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return path;
    }

    /**
     * 多文件保存方法
     * @author 子墨
     * @date 2018/10/13 23:38
     * @params [fileList]
     * @return java.lang.String
     */
    public String savaFile(MultipartFile[] fileList){
        String result = "";
        String path = null;
        File dir = new File(uploadPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        for(int i = 0;i < fileList.length;i++){
            MultipartFile file = fileList[i];
            if(file != null){
                try {
                    path = doSave(uploadPath,file);
                    result = (i + 1) == fileList.length ? result + path : result + path + "&";
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return result;
    }

    /**
     * 保存单个文件到某个路径下
     * @author 子墨
     * @date 2018/10/14 9:57
     * @params [saveDir, file]
     * @return java.lang.String
     */
    private String doSave(String saveDir,MultipartFile file) throws IOException {
        int index = file.getOriginalFilename().lastIndexOf(".");
        if (index == -1){
            return null;
        }
        String type = file.getOriginalFilename().substring(index);
        String fileName = UUID.randomUUID().toString().replaceAll("-","") + type;
        File serverFile = new File(saveDir,fileName);
        file.transferTo(serverFile);
        return fileName;
    }

}
